from settings.config import config
import requests
import time


class TokenManager(object):
    def __init__(self):
        self.access_token = None
        self.access_token_time = None

    def get_access_token(self):
        if self.access_token and self.access_token_time:
            diff = int(time.time()) - self.access_token_time
            if diff < 7000:
                return self.access_token
        try:
            resp = requests.get(config.get_access_token_url(), verify=False)
            self.access_token = resp.json().get('access_token')
            self.access_token_time = int(time.time())
        except Exception:
            pass
        return self.access_token

    def upload_material(self, material_type, file_path):
        access_token = self.get_access_token()
        url = 'https://api.weixin.qq.com/cgi-bin/media/upload' \
              '?access_token={0}&type={1}'.format(access_token, material_type)
        files = {
            'media': open(file_path, 'rb')
        }
        resp = requests.post(url, data=None, files=files)
        try:
            print('resp.json()', resp.json())
            if material_type == 'thumb':
                media_id = resp.json().get('thumb_media_id', None)
        except Exception:
            media_id = None
        return media_id

    def send_kf_msg(self, msg):
        access_token = self.get_access_token()
        url = 'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={}'.format(access_token)
        resp = requests.post(url, msg, verify=False)
        print(resp.json())
